
var Vouchers = {
   
    init: function() {
        this.bindActions();
        this.setupDataTable();
    },
    
    bindActions: function() {
        $("#generate_btn").click(function() {
            var url = $(this).data('url');
            
            $.get(url, function(data) {
                Jlib.showDialog({
                    title: 'Generate Vouchers',
                    content: data,
                    height: 530,
                    buttons: {
                        'Generate': function() {
                            Jlib.submitDialog();
                        },
                        'Cancel': function() {
                            Jlib.closeDialog();
                        }
                    },
                    load: function() {
                        Vouchers.setupGeneratorDialog();
                    },
                    close: function() {
                        window.history.go(0);
                    }
                });
            });
        });
    },
    
    setupDataTable: function() {
        $(".datatable tbody tr").click(function() {
            $(".datatable tbody tr").removeClass("selected");
            $(".datatable tbody tr").find("input[type=checkbox]").removeAttr("checked", "checked");
            
            $(this).addClass("selected");
            $(this).find("input[type=checkbox]").attr("checked", "checked");
            
            var url = $(this).data('url');
            
            $.get(url, function(data) {
                $("#voucher_details").html(data);
            });
        });
    },
    
    
    setupGeneratorDialog: function() {
        var self = this;
        
        $(".prefix, .postfix, .seq").attr("disabled", true);
        
        $("#scheme").change(function() {
            var val = $(this).val();
            var els = {
                'seq': '.seq', 
                'pre':'.prefix', 
                'post':'.postfix'
            };
            
            for(var a in els) {
                if( els.hasOwnProperty(a) ) {
                    val.indexOf(a) > -1 ? $( els[a] ).removeAttr("disabled") : $( els[a] ).attr("disabled", true);
                }
            }
            
            self.generateSamples();
        });
        
        $("#start_num, #prefix, #postfix, #total_num, #numbers_only").keyup(function() {
            self.generateSamples();
        }).change(function() {
            self.generateSamples();
        });
        
        $("#expiry_dt").datepicker({
            minDate: new Date(),
            dateFormat: 'yy-mm-dd'
        });
    },
    
    generateSamples: function() {
        var scheme = $("#scheme").val();
        var first = null; 
        var last = null;
        
        var start_num = $("#start_num").val(),
            last_num = ( parseInt($("#start_num").val()) + parseInt($("#total_num").val()) );
            
        var next_auto_id = 10, next_id = this.pad(next_auto_id + "", 2),
            prefix = $("#prefix").val(),
            postfix = $("#postfix").val(),
            numbers_only = $("#numbers_only").is(":checked");
        
        if( scheme == "rand" ) {
            first = this.getRandomCharacters(12, numbers_only);
            last = this.getRandomCharacters(12, numbers_only);
        }
        
        else if( scheme == "seq" ) {
            first = next_id + this.getRandomCharacters(4, numbers_only) + start_num;
            last = next_id + this.getRandomCharacters(4, numbers_only) + last_num;
        }
        
        else if( scheme == "seq_pre" ) {
            first = prefix + next_id + this.getRandomCharacters(3, numbers_only) + start_num;
            last = prefix + next_id + this.getRandomCharacters(3, numbers_only) + last_num;
        }
        
        else if( scheme == "seq_post" ) {
            first = next_id + this.getRandomCharacters(3, numbers_only) + start_num + postfix;
            last = next_id + this.getRandomCharacters(3, numbers_only) + last_num + postfix;
        }
        
        else if( scheme == "seq_pre_post" ) {
            first = prefix + next_auto_id + this.getRandomCharacters(3,numbers_only) + start_num + postfix;
            last = prefix + next_auto_id + this.getRandomCharacters(3,numbers_only) + last_num + postfix;
        }
        
        $("#first_val").html( first );
        $("#last_val").html( last );
    },
    
    pad: function (str, max) {
        return str.length < max ? this.pad("0" + str, max) : str;
    },
    
    getRandomCharacters: function(length, numbers_only) {
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
        var string_length = length ? length : 4;
        var myrnd = [], pos;
        
        if( numbers_only ) {
            chars = "0123456789";
        }

        // loop as long as string_length is > 0
        while (string_length--) {
            // get a random number between 0 and chars.length - see e.g. http://www.shawnolson.net/a/789/make-javascript-mathrandom-useful.html
            pos = Math.floor(Math.random() * chars.length);
            // add the character from the base string to the array
            myrnd.push(chars.substr(pos, 1));
        }

        // join the array using '' as the separator, which gives us back a string
        return myrnd.join(''); // e.g "6DMIG9SP1KDEFB4JK5KWMNSI3UMQSSNT"
    }
};

$(document).ready(function() {
    Vouchers.init();
});

